package org.springblade.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取特检院 Cookie，频繁改密码的话，要沟通
 * @author: Sharry
 * @createTime: 2024-01-04 17:05
 * @version: Version-1.0
 */
public class CookieUtil {
	public static String getCookie(){
		List<String> cookieList = new ArrayList<>();
		try {
			// 定义目标 URL
			URL url = new URL("http://wsbj2.gdsei.org.cn:8078/seimis/loginAction.do?method=login_JG_submit");

			// 打开连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			// 设置请求方法
			connection.setRequestMethod("POST");
			// post请求里面，参数要放在 http正文内，因此需要设为 true
			connection.setDoOutput(true);
			// 设置 http 正文 内容，也就是 form 表单提交的内容
			String data = "ISWBZH=1&j_password_md5=05db513382ac922393abcca69dbcf7e1&ISWBZH=1&j_password_md5=&j_username=WB01625&j_password=YHjd%3F836942";
			// 把数据以流的方式写给服务器
			connection.getOutputStream().write(data.getBytes());
			// 获取响应码
			int responseCode = connection.getResponseCode();
			System.out.println("Response Code: " + responseCode);

			// 读取响应内容
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine;
			StringBuilder content = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				content.append(inputLine);
			}
			in.close();

			// 获取响应头中的 Cookie
			Map<String, List<String>> headerFields = connection.getHeaderFields();
			List<String> cookies = headerFields.get("Set-Cookie");
			if (cookies != null) {
				cookieList = cookies;
			} else {
			}
			// 关闭连接
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String result = getResult(cookieList);
		return result;
	}

	public static String getResult(List<String> cookieList){
		String result = "";

		/**
		 * cookieList.toString打印出来的结果为：
		 * [iswbzh=1; Expires=Sat, 03-Feb-2024 08:57:45 GMT, cd_WB01625=""; Expires=Sat, 03-Feb-2024 08:57:45 GMT, JSESSIONID=746A80D71D3FBAE4BB2E8FFB262235F3; Path=/seimis]
		 */
		// 1. 获取cookieList iswbzh
		String iswbzh = cookieList.get(0).split(";")[0];
		// 2. 获取cookieList cd_WB01625
		String cd_WB01625 = cookieList.get(1).split(";")[0];
		// 3. 获取cookieList JSESSIONID
		String JSESSIONID = cookieList.get(2).split(";")[0];
		// 4. 拼接结果 iswbzh=1; cd_WB01625=""; JSESSIONID=746A80D71D3FBAE4BB2E8FFB262235F3
		result = iswbzh + "; " + cd_WB01625 + "; " + JSESSIONID;
		return result;
	}
}
